package abacab.remote.utils;

import static abacab.ext.RemotingExtension.PROTOCOL;
import abacab.remote.Connection;

/**
 * Utility methods
 */
public class RemoteUtils {
	/**
	 * Transforms a path to the local version
	 * 
	 * @param remotePath
	 *          the remote path
	 * @return the local path
	 * @throws IllegalArgumentException
	 *           if the path is invalid
	 */
	public static final String toLocalPath(String remotePath) throws IllegalArgumentException {
		if (!remotePath.startsWith(PROTOCOL)) {
			throw new IllegalArgumentException("A remote path must at least start with " + PROTOCOL + ": " + remotePath);
		}
		int idx = remotePath.indexOf('/', PROTOCOL.length());
		if (idx < 0) {
			throw new IllegalArgumentException("A remote path must provide a host & optionaly a port: " + remotePath);
		}
		return remotePath.substring(idx);
	}

	/**
	 * Transforms a path to the remote version
	 * 
	 * @param connection
	 *          the connection
	 * @param remoteLocalPath
	 *          the local path on the remote system
	 * @return the local path
	 * @throws IllegalArgumentException
	 *           if the path is invalid
	 */
	public static final String toRemotePath(Connection connection, String remoteLocalPath)
			throws IllegalArgumentException {
		if (!remoteLocalPath.startsWith("/")) {
			throw new IllegalArgumentException("A local path must at least start with '/': " + remoteLocalPath);
		}
		return PROTOCOL + connection.getRemoteHostPort() + remoteLocalPath;
	}
}